import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private DatagramSocket socket = null;
    private String serverIp;
    private int serverPort;

    public UdpEchoClient(String serverIp,int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket();
    }

    public void start() throws IOException {
        Scanner sc = new Scanner(System.in);
        // 1. 从标准输入读入一个数据
        System.out.println("->");
        String request = sc.nextLine();
        if (request.equals("exit")){
            System.out.println("exit!");
            return;
        }
        // 2. 把一个字符串构成一个 UDP 请求
        DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                InetAddress.getByName(serverIp),serverPort);
        socket.send(requestPacket);
        // 3. 尝试从服务器读取响应
        DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
        socket.receive(responsePacket);
        String response = new String(responsePacket.getData(),0, responsePacket.getLength());
        // 4. 显式这个结果
        String log = String.format("req: %s; resp: %s",request,response);
        System.out.println(log);
    }
    public static void main(String[] args) throws IOException {
        UdpEchoClient client = new UdpEchoClient("192.168.121.131",9090);
        client.start();
    }
}
